package com.hillky.springboot.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hillky.springboot.controller.request.BaseRequest;
import com.hillky.springboot.entity.User;
import com.hillky.springboot.exception.ServiceException;
import com.hillky.springboot.mapper.UserMapper;
import com.hillky.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> list(){
        return userMapper.list();
    }

    @Override
    public PageInfo<User> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<User> users = userMapper.listByCondition(baseRequest);
        return new PageInfo<>(users);
    }

    @Override
    public void save(User user) {
        Date date = new Date();
        user.setUsername(DateUtil.format(date,"yyyyMMdd")+Math.abs(IdUtil.fastSimpleUUID().hashCode()) );
        userMapper.save(user);
    }

    @Override
    public User getById(Integer id) {
        User user=userMapper.getById(id);
        return user;
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(new Date());
        userMapper.update(user);
        return;
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
        return;
    }

    @Override
    public void handleAccount(User user) {
        //查询数据库对象
        Integer userId = user.getId();
        User dbUser = userMapper.getById(userId);

        if(ObjectUtil.isNull(dbUser)){
            throw new ServiceException("数据异常");
        }
        dbUser.setAccount(dbUser.getAccount()+user.getScore());
        userMapper.update(dbUser);
    }
}
